package com.hcy.app.utils

class SimpleSnowflake(private val workerId: Long) {
    private var sequence = 0L
    private var lastTimestamp = -1L

    private val epoch = 1609459200000L  // 2021-01-01 00:00:00 UTC

    @Synchronized
    fun nextId(): Long {
        var currentTimestamp = System.currentTimeMillis()

        if (currentTimestamp < lastTimestamp) {
            throw RuntimeException("时钟回拨！")
        }

        if (currentTimestamp == lastTimestamp) {
            sequence = (sequence + 1) and 0xFFF  // 12位序列号
            if (sequence == 0L) {
                currentTimestamp = waitNextMillis(lastTimestamp)
            }
        } else {
            sequence = 0
        }

        lastTimestamp = currentTimestamp

        return ((currentTimestamp - epoch) shl 22) or
                (workerId shl 12) or
                sequence
    }

    private fun waitNextMillis(lastTimestamp: Long): Long {
        var timestamp = System.currentTimeMillis()
        while (timestamp <= lastTimestamp) {
            timestamp = System.currentTimeMillis()
        }
        return timestamp
    }
}

// 使用
//fun main() {
//    val generator = SimpleSnowflake(workerId = 1)
//    println("生成的ID: ${generator.nextId()}")
//}